package com.caltco.cargo.ops.modules.sys.service.impl;

import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/{userId}") // 连接时带上 userId
@Component
public class WebSocketServer {
    // 存储用户ID和多个Session
    static final ConcurrentHashMap<Long, List<Session>> userSessions = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(@PathParam("userId") Long userId, Session session) {
        userSessions.computeIfAbsent(userId, k -> new ArrayList<>()).add(session);
        System.out.println(userSessions);
        System.out.println("用户 " + userId + " 在新设备连接！");
    }

    @OnClose
    public void onClose(@PathParam("userId") Long userId, Session session) {
        userSessions.getOrDefault(userId, new ArrayList<>()).remove(session);
        if (userSessions.get(userId).isEmpty()) {
            userSessions.remove(userId);
        }
        System.out.println("用户 " + userId + " 设备断开");
    }

    // 给所有该用户的设备发送消息
    public static void sendMessageToUser(Long userId, String message) {

        List<Session> sessions = userSessions.get(userId);
        if (sessions != null) {
            sessions.removeIf(session -> !session.isOpen());  // 移除那些已经关闭的会话
            for (Session session : sessions) {
                try {
                    session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
